package com.gt.utils;

import lombok.extern.log4j.Log4j2;
import okhttp3.HttpUrl;
import org.springframework.stereotype.Component;

/**
 * @Auther: jc
 * @Date: 2020/7/3 10:19
 * @Description:微信请求类
 */

@Component
@Log4j2
public class WechatPayHttpClient {

    /*public static JSON doGet(String url) throws Exception {

        CloseableHttpClient httpclient = null;
        JSONObject result = new JSONObject();
        CloseableHttpResponse response = null;

        try {

            ClassLoader classLoader = WechatPayHttpClient.class.getClassLoader();

            WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                    .withMerchant(WechatConfig.merchantId, WechatConfig.certificateSerialNo, PemUtil.loadPrivateKey(classLoader.getResourceAsStream(WechatConfig.privateKeyFilePath)));

            InputStream inputStream = classLoader.getResourceAsStream(WechatConfig.wechatpayCertificatePath);
            if(inputStream != null){

                List<X509Certificate> certs = new ArrayList<>();
                certs.add(PemUtil.loadCertificate(inputStream));
                builder.withWechatpay(certs);

            }else{

                AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                        new WechatPay2Credentials(WechatConfig.merchantId,new PrivateKeySigner(WechatConfig.certificateSerialNo, PemUtil.loadPrivateKey(classLoader.getResourceAsStream(WechatConfig.privateKeyFilePath)))),
                        WechatConfig.apiV3Key.getBytes("utf-8"));
                builder.withValidator(new WechatPay2Validator(verifier));

            }

            // 创建Httpclient对象
            httpclient = builder.build();

            // 创建http GET请求
            HttpUrl httpUrl = HttpUrl.parse(url);
            String authorization = WechatConfig.schema + " " + getToken("GET",httpUrl,"");

            String uri = WechatConfig.innerRedirectUrl + "wxcert" + httpUrl.encodedPath();
            if (httpUrl.encodedQuery() != null) {
                uri += "?" + httpUrl.encodedQuery();
            }

            HttpGet httpGet = new HttpGet(uri);
            httpGet.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
            httpGet.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            httpGet.setHeader(HttpHeaders.AUTHORIZATION, authorization);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            int statusCode = response.getStatusLine().getStatusCode();
            String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            result = JSON.parseObject(resultString);
            result.put("statusCode",statusCode);

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e);
            throw e;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if(httpclient != null){
                    httpclient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                log.error(e);
            }
        }
        return result;
    }*/

    /*public static JSON doPost(String url, JSON json) throws Exception {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        JSONObject result = new JSONObject();

        try {

            ClassLoader classLoader = WechatPayHttpClient.class.getClassLoader();

            WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                    .withMerchant(WechatConfig.merchantId, WechatConfig.certificateSerialNo, PemUtil.loadPrivateKey(classLoader.getResourceAsStream(WechatConfig.privateKeyFilePath)));

            InputStream inputStream = classLoader.getResourceAsStream(WechatConfig.wechatpayCertificatePath);
            if(inputStream != null){

                List<X509Certificate> certs = new ArrayList<>();
                certs.add(PemUtil.loadCertificate(inputStream));
                builder.withWechatpay(certs);

            }else{

                AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                        new WechatPay2Credentials(WechatConfig.merchantId,new PrivateKeySigner(WechatConfig.certificateSerialNo, PemUtil.loadPrivateKey(classLoader.getResourceAsStream(WechatConfig.privateKeyFilePath)))),
                        WechatConfig.apiV3Key.getBytes("utf-8"));
                builder.withValidator(new WechatPay2Validator(verifier));

            }

            // 创建Httpclient对象
            httpclient = builder.build();

            // 创建Http Post请求
            HttpUrl httpUrl = HttpUrl.parse(url);
            String authorization = WechatConfig.schema + " " +  getToken("POST",httpUrl,json.toJSONString());

            String uri = WechatConfig.innerRedirectUrl + "wxcert" + httpUrl.encodedPath();
            if (httpUrl.encodedQuery() != null) {
                uri += "?" + httpUrl.encodedQuery();
            }

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
            httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            httpPost.setHeader(HttpHeaders.AUTHORIZATION, authorization);

            if(json != null){
                // 创建请求内容
                StringEntity entity = new StringEntity(json.toJSONString(), ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
            }

            // 执行http请求
            response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            result = JSON.parseObject(resultString);
            result.put("statusCode",statusCode);

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e);
            throw e;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if(httpclient != null){
                    httpclient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                log.error(e);
            }
        }

        return result;
    }*/

    /*static String getToken(String method, HttpUrl url, String body) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        String nonceStr = RandomStringUtils.randomAlphabetic(10);
        long timestamp = System.currentTimeMillis() / 1000;
        String message = buildMessage(method, url, timestamp, nonceStr, body);
        String signature = sign(message.getBytes("utf-8"));

        return "mchid=\"" + WechatConfig.merchantId + "\","
                + "nonce_str=\"" + nonceStr + "\","
                + "timestamp=\"" + timestamp + "\","
                + "serial_no=\"" + WechatConfig.certificateSerialNo + "\","
                + "signature=\"" + signature + "\"";
    }

    static String sign(byte[] message) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        Signature sign = Signature.getInstance("SHA256withRSA");
        sign.initSign(PemUtil.loadPrivateKey(WechatPayHttpClient.class.getClassLoader().getResourceAsStream(WechatConfig.privateKeyFilePath)));
        sign.update(message);

        return Base64.getEncoder().encodeToString(sign.sign());
    }*/

    static String buildMessage(String method, HttpUrl url, long timestamp, String nonceStr, String body) {
        String canonicalUrl = url.encodedPath();
        if (url.encodedQuery() != null) {
            canonicalUrl += "?" + url.encodedQuery();
        }

        return method + "\n"
                + canonicalUrl + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + body + "\n";
    }

}
